<?php
/**
 * Author : Traveler.
 * Time   : 2021/8/31 14:56
 */

namespace sunshine;


use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Request;
use think\Response;
use Throwable;
use sunshine\exceptions\ApiException;

/**
 * Api异常处理类
 *
 * @package app
 */
class ApiExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     *
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * 处理异常
     *
     * @param Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        }

        $data = $this->collectExceptionData($e);

        if ($e instanceof ApiException || $e instanceof HttpException) {
            $statusCode = $e->getStatusCode();
            $headers    = $e->getHeaders();
        }

        return app('json')->code($statusCode ?? 500)->header($headers ?? [])->json($data);
    }

    /**
     * 收集异常数据
     *
     * @param Throwable $e
     * @return array
     */
    private function collectExceptionData(Throwable $e): array
    {
        if ($this->app->isDebug()) {
            $data = [
                'code'    => $e->getCode(),
                'message' => $e->getMessage(),
                'file'    => $e->getFile(),
                'line'    => $e->getLine(),
            ];
        } else {
            $data = $e instanceof ApiException ? [
                'code'    => $this->getCode($e),
                'message' => $this->getMessage($e),
                'data'    => null
            ] : [];
        }

        return $data;
    }
}
